import type { InternalAxiosRequestConfig } from "axios";

import { ref, reactive, onBeforeMount, watch } from "vue";

import http from "@/api";

interface QueueConfig extends InternalAxiosRequestConfig {
  queueId?: string;
}

const useLoading = (delay: number = 500) => {
  const queueLoading = ref(false);

  const queueId = ref<string | undefined>();

  const queueGroup = reactive<string[]>([]);

  const queueReset = () => {
    queueId.value = (Math.random() + Date.now()).toString(36);
  };

  onBeforeMount(() => {
    queueReset();
    http.service.interceptors.request.use(async (config: QueueConfig) => {
      if (!!config.queueId) {
        queueGroup.push(config.queueId);
      }
      return config;
    });
    http.service.interceptors.response.use(data => {
      const timer = setTimeout(() => {
        queueGroup.shift();
        clearTimeout(timer);
      }, delay);
      return data;
    });
  });

  watch(queueGroup, () => {
    const timer = requestAnimationFrame(() => {
      if (queueGroup.length === 0) {
        queueId.value = undefined;
      }
      queueLoading.value = !!queueGroup.length;
      cancelAnimationFrame(timer);
    });
  });

  return {
    queueLoading,
    queueId,
    queueReset
  };
};

export default useLoading;
